<!-- equipmentLedger -->
<template>
    <PageWrapper v-loading="loading" loading-tip="加载中...">
      <div class="p-4 p-4-tag">
        <div class="tag" :class="isCloseTree ? 'tag-nav-close' : ''">
          <div class="main-content">
            <div class="form-box">
              <BasicForm @register="registerForm">
                  <template #slotBtns class="page-form-slotbtn">
                    <div class="btn-box">
                      <a-button class="btn-box-item" @click="throttleReset" style="margin-right:10px">重置</a-button>
                      <a-button class="btn-box-item" type="primary" @click="throttleSubmit"
                        >查询</a-button
                      >
                      
                    </div>
                  </template>
              </BasicForm>
            </div>
            <BasicTable
              @register="registerTable"
              :columns="columns"
              :dataSource="tableData"
              :canResize="false"
              :clickToRowSelect="false"
              :showIndexColumn="true"
              :striped="true"
              :bordered="true"
              :pagination="false"
              :actionColumn="hasPermission(['3-1-update', '3-1-del']) ? actionColumn : undefined"
              rowKey="code"
            >
              <template #bodyCell="{ column, record }">
                <!-- 报警状态开启红色，应答绿色，关闭灰色 -->
                  <template v-if="column.key === 'AlarmStatus_text'">
                    <span :class="record[column.key] === '开启'?'red':record[column.key] === '应答'?'green':'gray'">
                      {{ record[column.key] }}
                    </span>
                </template>
                <template v-if="column.key === 'AlarmLevel_text'">
                    <span :style="{ color: `${levelColorObj[record[column.key]]}` }">
                      {{ record[column.key] }}
                    </span>
                </template>
                <template v-if="column.key === 'action'">
                  <TableAction
                    :actions="[
                     {
                      label: '详情',
                      onClick: handleSet.bind(null, record),
                    },
                    ]"
                  />
                </template>
              </template>
            </BasicTable>
            <div class="flex py-2 items-center justify-end pagination-box">
              <a-pagination
                :show-total="(total) => `共 ${total} 条数据`"
                showSizeChanger
                size="small"
                :current="paginationInfo.data.current"
                :pageSize="paginationInfo.data.pageSize"
                :total="paginationInfo.data.total"
                @change="handlePageChange"
              />
            </div>
          </div>
        </div>
        <!-- 详情 -->
        <modelByDetail
            class="model"
            :info="attributeForm"
                @register="register"
            @submit-success="handleUpdateDeatil"
        />
      </div>
    </PageWrapper>
  </template>
  
  <script setup lang="ts">
    import { PageWrapper } from '/@/components/Page';
    // eslint-disable-next-line
    import { ref, onMounted, reactive, h, unref, nextTick } from 'vue';
    import { usePermission } from '/@/hooks/web/usePermission';
    import { BasicTable, TableAction, useTable } from '/@/components/Table';
    import { BasicColumn } from '/@/components/Table/src/types/table';
    import { useI18n } from '/@/hooks/web/useI18n';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
    import { Pagination } from 'ant-design-vue';
    import { getdevicetypes } from '/@/api/equipmentType/index';
    import { getdevicemodels, getdatalist } from '/@/api/equipmentModel/index';
    import { useDebounceFn } from '@vueuse/core';
    import { getequipmentinfo, getdownloadrecord} from '/@/api/equipmentControl/index';
    import modelByDetail from '/@/views/project/equipmentControl/components/modelByDetail.vue';
    import { useModal } from '/@/components/Modal';
    import dayjs from 'dayjs';
    import { useGo } from '/@/hooks/web/usePage';
  
    const go = useGo();
    const APagination = Pagination;
    let loading = ref(false);
    let tableData = reactive([]);
    // 设备类型
    let deviceTypeList = [];
    // 设备型号
    let deviceModelList = [];
    
    let isCloseTree = ref(false);
    //添加属性弹窗
    let attributeForm = reactive({
        data: {}
    });
    
    const throttleSubmit = useDebounceFn(handleSubmit, 500);
    const throttleReset = useDebounceFn(handleResetFields, 500);
    const { hasPermission } = usePermission();
    const { createConfirm, createMessage } = useMessage();
    const [register, { openModal, closeModal }] = useModal();
    //报警级别颜色
    const levelColorObj = {
      '提示': '#3399CC',
      '轻微': '#33CCCC',
      '一般': '#FFCC00',
      '严重': '#FF9999',
      '紧急': '#993399'
    }
    
    // 表单内容
    const schemas: FormSchema[] = [
      {
        field: 'TypeCode',
        component: 'Select',
        label: '设备类型：',
        colProps: {
          span: 4,
        },
        componentProps: {
          options: [],
          fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
          onChange: (e) => {
            nextTick(()=>{
              getDriverinfo()
            })
            
          },
        },
      },
      {
        field: 'ModelCode',
        component: 'Select',
        label: '设备型号：',
        colProps: {
          span: 4,
        },
        componentProps: {
          options: [],
          fieldNames: { label: 'Name', value: 'Code', key: 'Code' },
          onChange: (e) => {
            nextTick(()=>{
              getDriverinfo()
            })
            
          },
        },
      },
      {
        label: '设备编码',
        field: 'AssetCode',
        component: 'ApiSelect',
        colProps: {
          span: 4,
        },
        componentProps: {
          options: [],
        },

      },
      {
        field: 'times',
        label: '下发日期',
        component: 'RangePicker',
        componentProps: {
          // 'YYYY-MM-DD HH:mm:ss'
          format: 'YYYY-MM-DD HH:mm:ss',
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
          placeholder: ['开始时间', '结束时间'],
          showTime: { format: 'HH:mm:ss' },
          ranges: { 现在: [dayjs(), dayjs()] },
        },
        colProps: {
          span: 6,
        },
      },
      {
        field: 'btns',
        component: 'Input',
        label: '',
        slot: 'slotBtns',
        colProps: {
          span: 4,
        },
      },
    ];
    const [registerForm, { validateFields, setFieldsValue, updateSchema, getFieldsValue }] = useForm({
      labelWidth: 100,
      schemas: schemas,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 24,
      },
    });
    const { t } = useI18n();
    // 分页信息
    let paginationInfo = reactive({
      data: {
        pageSize: 50,
        total: 0,
        current: 1,
      },
    });
  
    // 表格表头
    let columns: BasicColumn[] = [
    {
        title: '操作单号',
        dataIndex: 'OperationNO',
      },
      {
        title: '设备编码',
        dataIndex: 'AssetCode',
      },
      {
        title: '设备名称',
        dataIndex: 'DeviceName',
      },
      {
        title: '设备型号',
        dataIndex: 'ModelCode',
      },
      {
        title: '型号名称',
        dataIndex: 'ModelName',
      },
      {
        title: '设备类型',
        dataIndex: 'TypeName',
      },
      {
        title: '操作人',
        dataIndex: 'CreatedUserName',
      },
      {
        title: '下发时间戳',
        dataIndex: 'TimeStamp',
        width:180
      },
    ];
    // 操作栏
    let actionColumn = {
      width: 100,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
    };
  
    const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
    // 获取设备类型
    async function getDeviceTypes() {
      try {
        loading.value = true;
  
        let res = await getdevicetypes([
          {
            PageNO: 1,
            PageSize: 500,
          },
        ]);
        deviceTypeList = res.Rows;
        updateSchema({
          field: 'TypeCode',
          componentProps: {
            options: deviceTypeList,
          },
        });
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    }
    //获取设备编码列表
  async function getDriverinfo() {
    const {TypeCode,ModelCode,AssetCode} =  await getFieldsValue();
      try {
        loading.value = true;
          let params = {
              AssetCode: '',
              TypeCode: TypeCode, // 设备类型
              ModelCode: ModelCode,  // 设备型号
          };
          let res = await getequipmentinfo([params]);
          if(res){
            updateSchema({
              field: 'AssetCode',
              componentProps: {
                options: res.map((item)=>{
                  return {
                    label: item.AssetCode,
                    value: item.AssetCode
                  }
                }),
                
              },
            });
            
          }
          loading.value = false;
      } catch (error) {
        loading.value = false;
      }
  }
    // 获取设备型号
    async function getDeviceModels() {
      try {
        loading.value = true;
  
        let res = await getdevicemodels([
          {
            PageNO: 1,
            PageSize: 50,
          },
        ]);
        deviceModelList = res.Rows;
  
        updateSchema({
          field: 'ModelCode',
          componentProps: {
            options: deviceModelList,
          },
        });
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    }
    // 重置按钮点击事件
    async function handleResetFields() {
      initSearch();
      getTableData();
    }
    // 重置搜索条件
    function initSearch() {
      setFieldsValue({
        TypeCode: '',
        ModelCode: '',
        AssetCode: '',
        times: []
      });
      paginationInfo.data.current = 1;
    }
    // 查询按钮点击事件
    async function handleSubmit() {
      try {
        let res = await validateFields();
        let StartTime = Array.isArray(res.times) ? res.times[0] : '';
        let EndTime = Array.isArray(res.times) ? res.times[1] : '';
        res.StartTime = StartTime;
        res.EndTime = EndTime;
        getTableData(res);
      } catch {}
    }
    function handleSet(_record) {
        attributeForm.data = _record
        openModal()
    }
    // 分页事件
    function handlePageChange(page, pageSize) {
      paginationInfo.data.current = page;
      paginationInfo.data.pageSize = pageSize;
      getTableData();
    }
    // 获取下发列表集合
    async function getTableData(params = {}) {
      clearSelectedRowKeys();
      
      try {
        loading.value = true;
        let res = await getdownloadrecord([
          {
            PageNO: paginationInfo.data.current,
            PageSize: paginationInfo.data.pageSize,
            ...params,
          },
        ]);
        paginationInfo.data.total = res.Total;
        tableData = res.Items;
        loading.value = false;
      } catch (error) {
        loading.value = false;
      }
    }
   function handleUpdateDeatil() {}
   
    onMounted(async () => {
      getTableData();
      getDeviceTypes();
      getDeviceModels();
      getDriverinfo();
    });
  </script>
  <script lang="ts">
    export default {
      name: 'EquipmentLedgerIndexPage',
    };
  </script>
  <style lang="less" scoped>
    .p-4-tag {
      width: 100%;
      height: 100%;
      padding: 0px !important;
  
      .tag {
        position: relative;
        overflow: hidden;
        height: 100%;
        background-color: #fff;
  
        .search-box {
          display: flex;
          align-items: center;
  
          > .ant-btn-sm {
            height: 32px;
          }
        }
  
        .main-nav {
          position: absolute;
          top: 0;
          left: 0;
          bottom: 0;
          width: 240px;
          height: calc(100%);
          padding: 8px;
          box-sizing: border-box;
          overflow: auto;
          border-right: 1px solid #ccc;
  
          ::v-deep(.vben-tree__title) {
            user-select: none !important;
          }
        }
  
        .main-sidebar {
          position: absolute;
          top: 0;
          left: 240px;
          bottom: 0;
          width: 12px;
          border-radius: 5px;
          cursor: pointer;
          user-select: none;
  
          .close-btn {
            position: absolute;
            top: 50%;
            left: 0;
            width: 12px;
            height: 30px;
            margin-top: -50%;
  
            line-height: 30px;
            text-align: center;
            background: #7dcdfe;
            border-radius: 6px;
            color: #fff;
  
            > span {
              font-size: 12px !important;
            }
          }
        }
  
        .main-sidebar:hover {
          background-color: #e2e3e5;
        }
  
        .main-content {
          position: relative;
          height: 100%;
          //margin-left: 260px;
          overflow: hidden;
  
          .pagination-box {
            z-index: 9;
            padding: 10px 5px;
            box-sizing: border-box;
            position: absolute;
            width: 100%;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: #fff;
          }
        }
  
        .main-content::after {
          content: '';
          display: block;
          width: 100%;
          height: 45px;
        }
      }
  
      .tag-nav-close {
        .main-nav {
          left: -260px;
        }
  
        .main-sidebar {
          left: 0;
        }
  
        .main-content {
          margin-left: 20px;
        }
      }
    }
  
    .form-box {
      padding: 5px;
  
      ::v-deep(.ant-form-item) {
        margin: 0 5px;
        margin-bottom: 8px;
        
      }
    }
    .red{
      color: red
    }
    .green{
      color: green;
    }
    .gray{
      color: gray
    }
  </style>
  